﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class EducationLevelController : BaseController
    {
        public const int REQUEST_ACTIVE = 1;
        EducationLevelBO educationLevelBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(EducationLevelController));

        public ActionResult Index(EducationLevelModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (a == null) a = new EducationLevelModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[25] = "active";
                a.Deleted = 2;
                var model = search(a, pageIndex, currentId, false);
                return View("~/Views/EducationLevel/EducationLevel.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới trình độ học vấn
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateEducationLevel(string id)
        {
            try
            {
                EducationLevelModel model = null;
                if (!(String.IsNullOrEmpty(id) || String.IsNullOrWhiteSpace(id)))
                {
                    educationLevelBO = new EducationLevelBO();
                    model = new EducationLevelModel(educationLevelBO.GetEducationLevelById(id));
                }
                if (model == null)
                {
                    model = new EducationLevelModel();
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/EducationLevel/_EducationLevelModel.cshtml", model);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(EducationLevelModel aModel = null, int pageIndex = 0, string sort = "EducationLevelId", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (aModel == null) aModel = new EducationLevelModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                var model = search(aModel, pageIndex, currentId, false);
                return PartialView("~/Views/EducationLevel/_EducationLevelList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        //Define request: Active = 1
        public ActionResult actionActive(string id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    educationLevelBO = new EducationLevelBO();
                    bool result = educationLevelBO.activeEducationLevel(id, REQUEST_ACTIVE);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(new string[] { id }),
                            Resources.Localization.ActionActiveCaption + " - actionActive");

                        return Json(JsonResponse.Json200("Khôi phục trình độ học vấn thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// Thêm mới trình độ học vấn
        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateEducationLevel(EducationLevelModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    educationLevelBO = new EducationLevelBO();
                    bool result = educationLevelBO.createOrUpdateEducationLevel(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<EducationLevelModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateDrlsIssuer", model);

                        if (!(String.IsNullOrEmpty(model.Education_Level_ID) || String.IsNullOrWhiteSpace(model.Education_Level_ID)))
                        {
                            return Json(JsonResponse.Json200("Cập nhật trình độ học vấn thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới trình độ học vấn thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }
        //-----------------------------------------------------------------------------------
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] listID)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    educationLevelBO = new EducationLevelBO();
                    bool result = educationLevelBO.deleteEducationLevel(listID);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                          CommonData.AppName,
                          GetFunction(),
                          CommonData.GetListId(listID),
                          Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa trình độ học vấn thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<EducationLevelModel> search(EducationLevelModel myModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                educationLevelBO = new EducationLevelBO();

                var DALModel = educationLevelBO.GetDynamicListPaging(myModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var models = new DataPage<EducationLevelModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.EducationLevelModel gender in lstItem)
                {
                    models.Data.Add(new EducationLevelModel(gender));
                }

                EducationLevelModel model = null;
                if (!String.IsNullOrEmpty(currentId))
                {
                    model = models.Data.Find(user => user.Education_Level_ID.Equals(currentId));
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = myModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "EducationLevel",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "education-level-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch
            {
                throw;
            }
        }

        //Kiểm tra tên trình độ học vấn đã tồn tại chưa
        public JsonResult CheckExistEducationLevelName(string name, string Education_Level_ID)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(name))
                {
                    EducationLevelModel educationLevelModel = new EducationLevelModel()
                    {
                        Name = name.Trim(),
                        Deleted = 2

                    };
                    var model = search(educationLevelModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (EducationLevelModel educationLevel in lstItem)
                        {
                            if (!(String.IsNullOrEmpty(educationLevel.Education_Level_ID) || String.IsNullOrWhiteSpace(educationLevel.Education_Level_ID)))
                            {
                                if (!educationLevel.Education_Level_ID.Equals(Education_Level_ID))
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.EducationLevelNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã trình độ học vấn đã tồn tại chưa
        public JsonResult CheckExistEducationLevelCode(string code, string Education_Level_ID)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(code))
                {
                    EducationLevelModel educationLevelModel = new EducationLevelModel()
                    {
                        Code = code.Trim(),
                        Deleted = 2
                    };
                    var model = search(educationLevelModel, 0, string.Empty, true);
                    
                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (EducationLevelModel educationLevel in lstItem)
                        {
                            if (!educationLevel.Education_Level_ID.Equals(Education_Level_ID))
                            {
                                //Neu chinh sua thong tin ung dung thi chi kiem tra nhung ung dung khac co trung khong
                                if (educationLevel.Education_Level_ID != Education_Level_ID)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.EducationLevelCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Danh mục trình độ học vấn - EducationLevelController";
        }
    }
}